
package com.example.quicklaunch;

import java.util.Comparator;
import java.util.List;

/**
 * Compare with two matched AppItem.
 * 
 * @author admin
 */
public class AppComparetor implements Comparator<AppItem> {

    @Override
    public int compare(AppItem appItem1, AppItem appItem2) {
        final List<Integer> match1 = appItem1.getMatchedIndex();
        final List<Integer> match2 = appItem2.getMatchedIndex();
        final String label1 = appItem1.getLablePinyin();
        final String label2 = appItem2.getLablePinyin();
        /*
         * Sort order rules: 1. If matched length equals pinyin length. Means
         * head match. head match is highest priority-first 2. A bit comparison,
         * ex. 123 < 2 , 123 < 13 ..... 3. When bit comparison the same. compare
         * length , ex. 123 < 1234, 12 < 1234
         */
        if (match1.size() != 0 && match2.size() != 0) {
            if (match1.size() == label1.split(" ").length
                    && match2.size() != label2.split(" ").length) {
                return -1;
            } else if (match2.size() == label2.split(" ").length
                    && match1.size() != label1.split(" ").length) {
                return 1;
            }
            int length = match1.size() > match2.size() ?
                    match2.size() : match1.size();
            for (int index = 0; index < length; index++) {
                if (match1.get(index) < match2.get(index)) {
                    return -1;
                } else if (match1.get(index) > match2.get(index)) {
                    return 1;
                } else {
                    continue;
                }
            }
            if (match1.size() == match2.size()) {
                return 0;
            } else if (match1.size() > match2.size()) {
                return 1;
            } else {
                return -1;
            }
        } else if (match1.size() == 0 && match2.size() != 0) {
            return 1;
        } else if (match1.size() != 0 && match2.size() == 0) {
            return -1;
        } else {
            return 0;
        }
    }

}
